#!/usr/bin/env python3
# _*_ coding: utf-8 _*_

import os
import re


if __name__ == '__main__':
    files = sorted([file for file in os.listdir('.')
                    if re.match(r'^[0-9][0-9]\.tex', file)])
    tex = '\\documentclass[article]{mathart}\\author{sc@hsu.edu.cn}\n\\begin{document}'
    with open('main.tex') as f:
        content = f.read()
    chapter_title_m = re.search(r'\\renewcommand{\\mytitle}{([^}]*)}', content)
    if chapter_title_m:
        tex = '\n'.join([tex, f'\\title{{{chapter_title_m.group(1)}}}\\maketitle'])
    for file in files:
        with open(file) as f:
            content = f.read()
        section_title_m = re.search(r'\\section{.*$', content, re.M | re.A)
        section_title = section_title_m.group(0) if section_title_m else ''
        summary_m = re.search(r'\\begin{frame}{小结}(.*)\\end{frame}', content, re.S)
        if summary_m:
            summary = summary_m.group(1)
            tex = '\n'.join([tex, section_title, summary])
    tex = '\n'.join([tex, '\\end{document}'])
    with open('summary.tex', 'w') as f:
        f.write(tex)
